// 添加分类功能
function initAddCategoryPage() {
    const messageDiv = document.getElementById('message');
    const saveBtn = document.getElementById('save-btn');
    const addForm = document.getElementById('add-form');
    const logoutBtn = document.getElementById('logout-btn');

    // 显示用户信息
    async function showUserInfo() {
        try {
            const { data: { session } } = await supabase.auth.getSession();
            if (session) {

                getProById(session.user.id);
                const userEmail = document.getElementById('user-email');
                const userDisplayName = document.getElementById('user-display-name');
                const userAvatar = document.getElementById('user-avatar');
                showUserInfoCommon(session.user, userEmail, userDisplayName, userAvatar);
            } else {
                window.location.href = '../hc_login/index.html';
            }
        } catch (error) {
            console.error('加载用户信息错误:', error);
            showMessage(messageDiv, '加载用户信息失败', 'error');
        }
    }
   async function getProById(userid){
        /**/
        let query = supabase
            .from('hc_user_profiles')
            .select('*', { count: 'exact' })
            .eq('is_deleted', false)
            .eq('id',userid );
        const { data, error, count } = await query;
        if (data.length>0){
            document.getElementById('user-id').value = data[0].id;
            document.getElementById('id-card-number').value = data[0].id_card_number;
            document.getElementById('health-code').value = data[0].health_record_number;
            document.getElementById('username').value = data[0].username;

        }
        if (error) {
            throw error;
        }
    }
    // 保存
    async function saveCategory() {
        const { data: userData, error: userError } = await supabase.auth.getUser();
        if (userError || !userData.user) {
            showMessage(messageDiv, '用户未登录', 'error');
            return;
        }
        const userId = document.getElementById('user-id').value;
        const cardNum = document.getElementById('id-card-number').value;
        const healthCode = document.getElementById('health-code').value;
        const username = document.getElementById('username').value;

        // 验证必填字段
        if ( !cardNum || !healthCode ||  !username) {
            showMessage(messageDiv, '请填写所有必填字段', 'error');
            return;
        }

        try {
            setButtonLoading(saveBtn, true);
            const userDataObj = {
                id: userData.user.id,
                id_card_number: cardNum,
                health_record_number: healthCode,
                username:username,
                updated_at: new Date().toISOString()
            };
            let result;
            if (userId) {
                // 更新现有数据
                result = await supabase
                    .from('hc_user_profiles')
                    .update(userDataObj)
                    .eq('id', userId);
            } else {
                // 插入新数据
                result = await supabase
                    .from('hc_user_profiles')
                    .insert([userDataObj]);
            }

            const { error } = result;

            if (error) {
                throw error;
            }

            showMessage(messageDiv, userId ? '更新成功！' : '添加成功！', 'success');

        } catch (error) {
            console.error('添加错误:', error);
            showMessage(messageDiv, '添加失败: ' + error.message, 'error');
        } finally {
            setButtonLoading(saveBtn, false);
        }
    }

    // 表单提交
    if (addForm) {
        addForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            await saveCategory();
        });
    }

    // 退出登录
    if (logoutBtn) {
        logoutBtn.addEventListener('click', async () => {
            try {
                const { error } = await supabase.auth.signOut();
                if (error) throw error;
                window.location.href = '../hc_login/index.html';
            } catch (error) {
                console.error('退出登录错误:', error);
                showMessage(messageDiv, '退出登录失败: ' + error.message, 'error');
            }
        });
    }

    // 初始化页面
    showUserInfo();
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    initAddCategoryPage();
});